﻿using System;
using System.Diagnostics ;


namespace MskEdit.Dxf.Representation
{
    public struct DxfCodeTagPair
    {
        private string code_ ;
        private string tag_ ;


        public DxfCodeTagPair( string code, string tag ) {
            code_ = code ;
            tag_  = tag ;
        }
        
        
        public bool IsMatching( DxfCodeTagPair that ) {
            return this.IsMatching( that.code_, that.tag_ ) ;
        }
        

        public bool IsMatching( string code, string tag ) {
        
            Debug.Assert( !string.IsNullOrEmpty( code_ ) ) ;
            Debug.Assert( !string.IsNullOrEmpty( code  ) ) ;
            
            // Symmetric match rule for code
            
            if ( !code_.Equals( code ) )
                return false ;

            // Assymetric match rule for tag
            // NullOrEmpty tag match any tag, but
            // spesific tag matches only equal tag
            
            if ( !string.IsNullOrEmpty( tag_ ) )
                if ( !tag_.Equals( tag ) )
                    return false ;
                    
            return true ;
        }
        
        
        public bool IsFirst( string[] allLines, ref int lineNo ) {

            if ( allLines.Length < (lineNo + 2) ) 
                return false ;
        
            if ( !this.IsMatching( allLines[lineNo], allLines[lineNo + 1] ) )
                return false ;
            
            lineNo += 2 ;
            
            return true ;
        }


        public int? TryFindFirst( string[] allLines, ref int lineNo, int? fallbackValue ) {

            int internalLineNo = lineNo ;
            
            if ( allLines.Length < (internalLineNo + 2) ) 
                return fallbackValue ;
                  
            bool isFound = false ;
            
            for ( ; internalLineNo < allLines.Length; internalLineNo += 2 ) {
            
                if ( !this.IsMatching( allLines[internalLineNo], allLines[internalLineNo + 1] ) )
                   continue ;

                isFound = true ;
                break ;
            }

            if ( ! isFound )
                return fallbackValue ;
            
            lineNo = internalLineNo ;
            
            return internalLineNo ;
        }
    }
}
